#ifndef CUDPCLIENT_H
#define CUDPCLIENT_H

#include <QObject>
#include<QThread>
#include <QSemaphore>
#include <QMutex>

#include <QtNetwork/QUdpSocket>

/* UDP 客户端通信类 */
class CUdpBase : public QObject
{
	Q_OBJECT
public:
	explicit CUdpBase(QObject *parent = 0);
	~CUdpBase();

	// 绑定本地端口，用于接收数据
	bool BindLocalPort(qint16 localBind);

	/* 向服务器发送数据
	 * @param: data 发送数据内容
	 * @param: maxSize 发送数据长度
	 * @param: strIp 向谁发送数据
	 * @param: port 向哪个端口发送数据
	 * 返回发送数据长度
	 */
	qint64 Write(const char* data,
				 qint64 maxSize = -1,
				 QString strIp = "",
				 qint16 port = 0);

	void DisConn();

	/* 是否连接
	 * 2020-7-17 ls56647426@foxmail.com
	 */
	bool isConn();


signals:
	// 使用者可以connect 这个信号接收数据
	void sigDataReady(QByteArray);
	void sigWrite(const char *, qint64, QString, qint16);
	void sigDisConn();
	void sigBind(qint16);

public slots:
private slots:
	/* 数据接收槽函数 */
	void slot_dataReceived();
	void slotWrite(const char *pch, qint64, QString sendIp, qint16 sendPort);
	void slotDisConn();
	void slotBind(qint16 localBind);

private:

	bool m_isConn;
	QThread* m_thRecv;
	QUdpSocket* m_recvSock;  // 接收数据socket

	// bind
	QMutex m_lockBind;
	QSemaphore m_semBind;

	// write
	QMutex m_lockWrite;
	QSemaphore m_semWrite;
	QMutex m_lockWriteLen;
	qint64 m_iLen;
	QUdpSocket* m_sendSock; // 发送数据socket

	// Buffer
	QByteArray m_readBuf;

	// disconnect
	QMutex m_lockDisConn;
	QSemaphore m_semDisConn;

};

#endif // CUDPCLIENT_H
